
#include <Includes.h>

u8 u8RunningModeSet = dfRunningMode_Normal;  // 运行状态设置
u8 u8RunningModeStat = dfRunningMode_Normal; // 当前运行状态

void SetRunningMode(u8 mode)
{
    u8RunningModeSet = mode;
}

unsigned long TrimValue;
void ClockInit()
{
    // 配置24MHz HSI
    TrimValue = *(uint32_t *)(0x1fff0f10) + 30;
    RCC->ICSCR = (RCC->ICSCR & 0xFFFF0000) | (0x4 << 13) | TrimValue;

    __HAL_FLASH_SET_LATENCY(FLASH_LATENCY_0);

    // 设置HSI为系统时钟
    MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_SYSCLKSOURCE_HSI);

    // 设置HCLK分频
    MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE, RCC_CFGR_PPRE_1);
    SystemCoreClock = (HAL_RCC_GetSysClockFreq() >> ((AHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE) >> RCC_CFGR_HPRE_Pos]) & 0x1FU));
}

void Error_Handler(void)
{
    while (1)
    {
    }
}

void Uart_Init(void)
{
    UART_HandleTypeDef UartHandle;

    UartHandle.Instance = USART1;

    UartHandle.Init.BaudRate = 115200;
    UartHandle.Init.WordLength = UART_WORDLENGTH_8B;
    UartHandle.Init.StopBits = UART_STOPBITS_1;
    UartHandle.Init.Parity = UART_PARITY_NONE;

    UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE;
    UartHandle.Init.Mode = UART_MODE_TX_RX;

#ifdef DEF_OVERSAMPLING_8
    UartHandle.Init.OverSampling = UART_OVERSAMPLING_8;
#endif

    if (HAL_UART_DeInit(&UartHandle) != HAL_OK)
    { // 恢复默认
        Error_Handler();
    }
    if (HAL_UART_Init(&UartHandle) != HAL_OK)
    { // 初始化
        Error_Handler();
    }

    USART1->CR1 |= USART_CR1_RXNEIE | USART_CR1_TCIE;
}

void GPIO_Init(void)
{
    GPIO_InitTypeDef GPIO_InitStruct;

    GPIO_InitStruct.Pin = LED_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;

    HAL_GPIO_Init(LED_GPIO, &GPIO_InitStruct);

    GPIO_InitStruct.Pin = KEY_PIN;
    GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(KEY_GPIO, &GPIO_InitStruct);
    GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
    HAL_GPIO_Init(KEY_GPIO, &GPIO_InitStruct);
    HAL_NVIC_EnableIRQ(KEY_EXTNUMBER);
    HAL_NVIC_SetPriority(KEY_EXTNUMBER, 0, 0);
}

void BSP_Init(void)
{
    // PWR
    __HAL_RCC_PWR_CLK_ENABLE();

    ClockInit();
    HAL_Init();

    SPI_init();
    Configure_EXTI();
    GPIO_Init();
    Uart_Init();
    LPTIM_Init();
}

void LED_Toggle(void)
{
    HAL_GPIO_TogglePin(LED_GPIO, LED_PIN);
}

u8 KEY_Status(void)
{
    return HAL_GPIO_ReadPin(KEY_GPIO, KEY_PIN);
}
